<?php
if (!$_SESSION["loggedin"]){
  header("Location: ?q=login");
}
$reminders = simplexml_load_file('data/reminders.xml');

if(Util::HasValue($_POST['first'])){
  if (Util::IsPInt($_POST['index']) || $_POST['index'] === "0"){
    $tmp = $reminders->xpath("//reminder");
    $reminder = $tmp[$_POST['index']];
    if ($reminder["user"] == $_SESSION["username"]){
      $reminder->first = $_POST['first'];
      $reminder->last = $_POST['last'];
      $reminder->id = $_POST['id'];
      $reminder->class = $_POST['class'];
      $reminder->college = $_POST['college'];
      $reminder->withd = $_POST['withd'];
      $reminder->withdate = $_POST['withdate'];
      $reminder->enrstat = $_POST['enrstat'];
      $reminder->plnret = $_POST['plnret'];
      $reminder->specpgm = $_POST['specpgm'];
      $reminder->acadact = $_POST['acadact'];
      $reminder->email = $_POST['email'];
      $reminder->note = $_POST['note'];
      $reminder->reminder_date = $_POST['reminder_date'];
    }
  }else{
    $reminder = $reminders->addChild('reminder');
    $reminder["user"] = $_SESSION["username"];
    $reminder->addChild('first', $_POST['first']);
    $reminder->addChild('last', $_POST['last']);
    $reminder->addChild('id', $_POST['id']);
    $reminder->addChild('class', $_POST['class']);
    $reminder->addChild('college', $_POST['college']);
    $reminder->addChild('withd', $_POST['withd']);
    $reminder->addChild('withdate', $_POST['withdate']);
    $reminder->addChild('enrstat', $_POST['enrstat']);
    $reminder->addChild('plnret', $_POST['plnret']);
    $reminder->addChild('specpgm', $_POST['specpgm']);
    $reminder->addChild('acadact', $_POST['acadact']);
    $reminder->addChild('email', $_POST['email']);
    $reminder->addChild('note', $_POST['note']);
    $reminder->addChild('reminder_date', $_POST['reminder_date']);
  }
  $reminder["status"] = "okay";
  SaveReminders($reminders);
  
  //$reminders->asXML("data/reminders.xml");
  
  header("Location: ?q=reminders");
}

if ($args[1]=="create"){
  if (Util::IsPInt($args[2]) || $args[2] == 0){
    $index = $args[2];
    $tmp = $reminders->xpath("//reminder");
    $reminder = $tmp[$index];
  }
  $content = Template::Render("reminders.create", get_defined_vars());
}else if ($args[1]=="delete"){
  if (Util::IsPInt($args[2]) || $args[2] == 0){
    $index = $args[2];
    $tmp = $reminders->xpath("//reminder");
    $reminder = $tmp[$index];
    $reminder["status"] = "deleted";
    SaveReminders($reminders);
    header("Location: ?q=reminders");
  }
}

function SaveReminders($reminders){
  $dom = new DOMDocument('1.0');
  $dom->preserveWhiteSpace = false;
  $dom->formatOutput = true;
  $dom->loadXML($reminders->asXML(), LIBXML_NOBLANKS);
  $dom->save("data/reminders.xml");
}

?>